package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.core.redis.RedisCache;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.IotMsgNotifyData;
import com.zzyl.nursing.domain.IotMsgService;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Arrays;
import java.util.Map;

/**
 * 设备数据上报Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-06-09
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private IDeviceService iDeviceService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 查询设备数据上报
     * 
     * @param id 设备数据上报主键
     * @return 设备数据上报
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备数据上报列表
     * 
     * @param deviceData 设备数据上报
     * @return 设备数据上报
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData)
    {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增设备数据上报
     * 
     * @param deviceData 设备数据上报
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return save(deviceData) ? 1 : 0;
    }

    /**
     * 修改设备数据上报
     * 
     * @param deviceData 设备数据上报
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return updateById(deviceData) ? 1 : 0;
    }

    /**
     * 批量删除设备数据上报
     * 
     * @param ids 需要删除的设备数据上报主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备数据上报信息
     * 
     * @param id 设备数据上报主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Override
    public void devcieDateBatchSave(String contentStr) {
        //1.将string 数据转成我们的封装对象
        JSONObject jsonObject = JSONUtil.parseObj(contentStr);
        String jsonStr = JSONUtil.toJsonStr(jsonObject.get("notify_data"));
        IotMsgNotifyData iotMsgNotifyData = JSONUtil.toBean(jsonStr, IotMsgNotifyData.class);
        //2.设备id 查询数据库中是否有该设备
        Device device = iDeviceService.getOne(new LambdaQueryWrapper<Device>().eq(Device::getIotId, iotMsgNotifyData.getHeader().getDeviceId()));
        if(ObjectUtil.isEmpty(device)){
            throw new BaseException("该设备不存在，不能消费数据");
        }


        //3.组装数据
        IotMsgService iotMsgService = iotMsgNotifyData.getBody().getServices().get(0);

        LocalDateTime activeTime = LocalDateTimeUtil.parse(iotMsgService.getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
        //日期时区转换
        activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();

        Map<String, Object> properties = iotMsgService.getProperties();

        List<DeviceData> deviceDataList = new ArrayList<>();
        for(Map.Entry<String,Object> property : properties.entrySet()){
            DeviceData deviceData = new DeviceData();
            BeanUtil.copyProperties(device,deviceData,"id");
            deviceData.setFunctionId(property.getKey());
            deviceData.setDataValue(String.valueOf(property.getValue()));
            deviceData.setAlarmTime(activeTime);
            deviceData.setDeviceDescription(device.getDeviceDescription());
            deviceDataList.add(deviceData);
        }

        //批量添加设备模型数据
        this.saveBatch(deviceDataList);

        //把这个数据放redis 放一份
        redisTemplate.opsForHash().put("iot:product_data_latest",device.getIotId(),JSONUtil.toJsonStr(deviceDataList));

    }
}
